"""
配置管理模块
管理应用程序的设置和用户偏好
"""
import json
import os
from typing import Dict, Any


class ConfigManager:
    """配置管理器类"""
    
    def __init__(self, config_file: str = "config.json"):
        self.config_file = config_file
        self.default_config = {
            "download_path": "",
            "auto_naming": True,
            "concurrent_downloads": 3,
            "chunk_size": 8192,
            "timeout": 30,
            "max_retries": 3,
            "window_geometry": {"width": 800, "height": 600, "x": 100, "y": 100},
            "theme": "default",
            "language": "zh_CN"
        }
        self.config = self.load_config()
    
    def load_config(self) -> Dict[str, Any]:
        """加载配置文件"""
        try:
            if os.path.exists(self.config_file):
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    config = json.load(f)
                # 合并默认配置，确保所有键都存在
                for key, value in self.default_config.items():
                    if key not in config:
                        config[key] = value
                return config
            else:
                return self.default_config.copy()
        except (json.JSONDecodeError, IOError) as e:
            print(f"配置文件读取失败: {e}, 使用默认配置")
            return self.default_config.copy()
    
    def save_config(self) -> bool:
        """保存配置文件"""
        try:
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(self.config, f, indent=4, ensure_ascii=False)
            return True
        except IOError as e:
            print(f"配置文件保存失败: {e}")
            return False
    
    def get(self, key: str, default=None):
        """获取配置项"""
        return self.config.get(key, default)
    
    def set(self, key: str, value: Any):
        """设置配置项"""
        self.config[key] = value
    
    def update(self, updates: Dict[str, Any]):
        """批量更新配置"""
        self.config.update(updates)
    
    def reset_to_default(self):
        """重置为默认配置"""
        self.config = self.default_config.copy()